package com.cloud.wms.ui.sort.presenter;


import android.text.TextUtils;

import com.annimon.stream.Stream;
import com.cloud.core.base.BaseRxPresenter;
import com.cloud.core.http.error.ApiException;
import com.cloud.core.utils.MessageCreator;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.entity.ContainerEntity;
import com.cloud.wms.entity.Page;
import com.cloud.wms.http.Params;
import com.cloud.wms.http.observer.LoadingObserver;
import com.cloud.wms.http.observer.ResponseWrapper;
import com.cloud.wms.tools.PageHelper;
import com.cloud.wms.tools.RxUtils;
import com.cloud.wms.tools.TaskHelper;
import com.cloud.wms.ui.main.entity.RemoteEntity;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.ui.main.entity.UserEntity;
import com.cloud.wms.ui.sort.contract.CarSortDetachContract;
import com.cloud.wms.ui.sort.entity.BatchInfoEntity;
import com.cloud.wms.ui.sort.entity.BindInfoEntity;
import com.cloud.wms.ui.sort.entity.SortCommodityEntity;
import com.cloud.wms.ui.sort.entity.OrderEnum;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;


/**
 * @Author:Chen
 * @Date: 2021-01-14 15:51
 * @Description: 清点
 */
public class CarSortDetachPresenter extends BaseRxPresenter<CarSortDetachContract.View> implements CarSortDetachContract.Presenter {
    public static final int BATCH_LIST = 0x100;

    public static final int CHECK_BIND_CONTAINER = 0x109;

    public static final int BIND_CONTAINER = 0x101;

    public static final int CHECK_CONTAINER = 0x105;

    public static final int VERIFY_CONTAINER = 0x106;

    public static final int SORT_COMMODITY = 0x102;

    public static final int SUBMIT_SORT = 0x103;

    public static final int SORT_DETAIL = 0x104;

    public static final int SORT_POS_DETAIL = 0x110;

    public static final int SORT_COMPLETE = 0x107;

    public static final int TASK = 0x108;

    @Inject
    public CarSortDetachPresenter() {

    }

    /**
     * 检测波次是否绑定容器
     *
     * @param billId 关联单据ID
     */
    @Override
    public void checkBindContainer(long billId) {
        Params params = new Params();
        params.put("BillType", OrderEnum.Batch);
        params.put("BillID", billId);
        params.put("IsGetOrderInfo", true);

        FineExApplication
                .component()
                .http()
                .sortCheckBind(params)
                .map(new ResponseWrapper<>())
                .flatMap((Function<ArrayList<BindInfoEntity>, ObservableSource<ArrayList<BindInfoEntity>>>) bindInfoEntities -> {
                    if (bindInfoEntities == null || bindInfoEntities.size() == 0) {
                        return Observable.error(new ApiException("当前波次订单绑定信息查询失败！"));
                    }
                    ArrayList<BindInfoEntity> entities = (ArrayList<BindInfoEntity>) Stream.ofNullable(bindInfoEntities)
                            .sortBy(BindInfoEntity::getBindNum)
                            .toList();
                    return Observable.just(entities);
                })
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ArrayList<BindInfoEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ArrayList<BindInfoEntity> info) {
                        mView.showContent();
                        mView.onSuccess(MessageCreator.createMessage(info, CHECK_BIND_CONTAINER));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                        mView.showError();
                    }
                });
    }

    /**
     * 检查容器是否可用
     *
     * @param state
     * @param infoList
     * @param containerCode
     */
    @Override
    public void checkContainer(boolean state, ArrayList<BindInfoEntity> infoList, String containerCode) {
        if (state) {
            for (int i = 0; i < infoList.size(); i++) {
                BindInfoEntity entity = infoList.get(i);
                if (entity.getContainerCode().equalsIgnoreCase(containerCode)) {
                    mView.onSuccess(MessageCreator.createMessage(containerCode, VERIFY_CONTAINER));
                    return;
                }
            }
            mView.error("容器扫描错误，请检查！");
        } else {
            for (int i = 0; i < infoList.size(); i++) {
                BindInfoEntity entity = infoList.get(i);
                if (containerCode.equalsIgnoreCase(entity.getContainerCode())) {
                    mView.info("扫描容器已绑定，请勿重复绑定！");
                    return;
                }
            }

            Params params = Params.newInstance(Params.Type.WAREHOUSE);
            params.put("BoxCode", containerCode);
            FineExApplication
                    .component()
                    .http()
                    .checkContainerUseState(params)
                    .map(new ResponseWrapper<>())
                    .compose(mView.toLifecycle())
                    .compose(RxUtils.threadSwitch())
                    .subscribe(new LoadingObserver<ContainerEntity>(mView.provideContext()) {
                        @Override
                        public void onSuccess(ContainerEntity info) {
                            for (int i = 0; i < infoList.size(); i++) {
                                BindInfoEntity entity = infoList.get(i);
                                if (!entity.isState()) {
                                    entity.setContainerCode(info.getContainerCode());
                                    entity.setContainerID(info.getContainerID());
                                    entity.setState(true);
                                    break;
                                }
                            }
                            for (int j = 0; j < infoList.size(); j++) {
                                if (!infoList.get(j).isState()) {
                                    mView.onSuccess(MessageCreator.createMessage(false, CHECK_CONTAINER));
                                    return;
                                }
                            }
                            mView.onSuccess(MessageCreator.createMessage(true, CHECK_CONTAINER));
                            mView.info("已绑定完成，请确认绑定！");
                        }

                        @Override
                        public void onError(String msg) {
                            mView.error(msg);
                        }
                    });
        }
    }

    /**
     * 波次列表
     *
     * @param batchCode
     */
    @Override
    public void loadBatchList(String batchCode, int page) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        if (!TextUtils.isEmpty(batchCode)) {
            params.put("BatchCode", batchCode);
        }
        params.put("Sorting", "createDate");
        params.put("SkipCount", PageHelper.skipCount(page));
        params.put("MaxResultCount", PageHelper.PAGE_SIZE);
        params.put("BatchTypeID", "3");//1.散单分拣，2.单sku分拣，3.笼车分拣，4.团购分拣
        FineExApplication
                .component()
                .http()
                .sortBatchList(params)
                .map(new ResponseWrapper<>())
                .map(Page::getItems)
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ArrayList<BatchInfoEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ArrayList<BatchInfoEntity> info) {
                        if (page == 0) {
                            mView.onSuccess(MessageCreator.createMessage(info, PageHelper.LIST_NEW_DATA));
                        } else {
                            mView.onSuccess(MessageCreator.createMessage(info, PageHelper.LIST_NEXT_DATA));
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    @Override
    public void receiveTask(long billId, String taskCode) {
        FineExApplication
                .component()
                .http()
                .orderTaskList(billId + "")
                .map(new ResponseWrapper<>())
                .map(RemoteEntity::getItems)
                .flatMap((Function<ArrayList<TaskEntity>, ObservableSource<TaskEntity>>) Observable::fromIterable)
                .filter(taskEntity -> taskEntity.getTaskCode().equalsIgnoreCase(taskCode))
                .toList()
                .toObservable()
                .flatMap((Function<List<TaskEntity>, ObservableSource<TaskEntity>>) taskEntities -> {
                    if (taskEntities == null || taskEntities.isEmpty()) {
                        return Observable.error(new ApiException("暂无可领用任务"));
                    }
                    TaskEntity taskEntity = taskEntities.get(0);
                    Params params = new Params();
                    params.put("TaskID", taskEntity.getTaskID());
                    UserEntity userInfo = FineExApplication.component().loginCache().getUserInfo();
                    params.put("JobStationID", userInfo.getJobStationID());
                    params.put("ProductCategory", userInfo.getProductCategory());
                    params.put("ExecutorID", userInfo.getUserID());
                    return TaskHelper.receiveTask(params,taskEntity);
                })
                .flatMap((Function<TaskEntity, ObservableSource<TaskEntity>>) taskEntity -> {
                    Params params = new Params();
                    params.put("workId", taskEntity.getWorkID());
                    UserEntity userInfo = FineExApplication.component().loginCache().getUserInfo();
                    params.put("executerId", userInfo.getUserID());
                    return TaskHelper.executeTask(params)
                            .map(aVoid -> taskEntity);
                })
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<TaskEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(TaskEntity info) {
                        mView.onSuccess(MessageCreator.createMessage(info, TASK));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 绑定容器
     *
     * @param billId
     * @param containerCodes
     */
    @Override
    public void bindContainer(long billId, ArrayList<BindInfoEntity> containerCodes) {
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < containerCodes.size(); i++) {
            BindInfoEntity infoEntity = containerCodes.get(i);
            HashMap<String, Object> map = new HashMap<>();
            map.put("containerID", infoEntity.getContainerID());
            map.put("orderID", infoEntity.getBillID());
            map.put("num", (i + 1));
            list.add(map);
        }

        Params params = Params.newInstance(Params.Type.WAREHOUSE);
        params.put("orderType", 2);
        params.put("lstBox", list);
        params.put("userID", FineExApplication.component().loginCache().getUserInfo().getUserID());
        FineExApplication
                .component()
                .http()
                .sortBindContainer(params)
                .map(new ResponseWrapper<>())
                .flatMap((Function<Boolean, ObservableSource<Boolean>>) aBoolean -> {
                    if (!aBoolean) return Observable.error(new ApiException("绑定失败，请检查数据！"));
                    return Observable.just(true);
                })
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<Boolean>(mView.provideContext()) {
                    @Override
                    public void onSuccess(Boolean info) {
                        mView.onSuccess(MessageCreator.createMessage(info, BIND_CONTAINER));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 加载波次详情商品数据
     *
     * @param billId
     */
    @Override
    public void loadSortCommodity(long billId) {
        Params params = new Params();
        params.put("BatchID", billId);
        //1 边检边分-多笼车  2先拣后分-单笼车（东西拣到一起，需要二次分拨） 3单SKU分拣  4按订单分拣
        params.put("SortingType", 1);

        FineExApplication
                .component()
                .http()
                .sortBatchOrderDetail(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ArrayList<SortCommodityEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ArrayList<SortCommodityEntity> info) {
                        List<SortCommodityEntity> entities = Stream.ofNullable(info)
                                .sortBy(SortCommodityEntity::getPosCode)
                                .sortBy(sortCommodityEntity -> sortCommodityEntity.getNeedAmount() <= 0 ? 1 : -1)
                                .toList();

                        ArrayList<SortCommodityEntity> commodityBeans = new ArrayList<>();
                        for (int i = 0; i < entities.size(); i++) {
                            SortCommodityEntity commodityEntity = entities.get(i);
                            commodityEntity.setFlag(commodityEntity.getNeedAmount() <= 0);
                            if (commodityEntity.getNeedAmount() > 0) {
                                commodityBeans.add(commodityEntity);
                                for (int j = i + 1; j < entities.size(); j++) {
                                    if (commodityEntity.getPosID() == entities.get(j).getPosID() && entities.get(j).getNeedAmount() > 0) {
                                        commodityBeans.add(entities.get(j));
                                    }
                                }
                                break;
                            }
                        }
                        if (commodityBeans.isEmpty()) {
                            mView.onSuccess(MessageCreator.createMessage(commodityBeans, SORT_COMPLETE));
                        } else {
                            mView.onSuccess(MessageCreator.createMessage(commodityBeans, SORT_COMMODITY));
                        }
                        mView.onSuccess(MessageCreator.createMessage(getBatchPos(entities), SORT_POS_DETAIL));
                        mView.showContent();
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                        mView.showError();
                    }
                });
    }

    public List<SortCommodityEntity> getBatchPos(List<SortCommodityEntity> entities) {
        for (int i = 0; i < entities.size(); i++) {
            SortCommodityEntity entity = entities.get(i);
            entity.setFlag(entity.getNeedAmount() <= 0);
        }
        ArrayList<SortCommodityEntity> list = new ArrayList<>();
        Stream.ofNullable(entities)
                .groupBy(SortCommodityEntity::getPosCode)
                .forEach(entry -> {
                    SortCommodityEntity entity = new SortCommodityEntity();
                    entity.setPosCode(entry.getKey());
                    entity.setFlag(true);
                    List<SortCommodityEntity> value = entry.getValue();
                    for (int i = 0; i < value.size(); i++) {
                        SortCommodityEntity commodityEntity = value.get(i);
                        entity.setPosID(commodityEntity.getPosID());
                        entity.setBarCode(commodityEntity.getBarCode());
                        entity.setCommodityId(commodityEntity.getCommodityId());
                        if (!commodityEntity.isFlag()) {
                            entity.setFlag(false);
                        }
                    }
                    list.add(entity);
                });
        return Stream.ofNullable(list)
                .sortBy(SortCommodityEntity::getPosCode)
                .sorted((o1, o2) -> {
                    boolean o1Flag = o1.isFlag();
                    boolean o2Flag = o2.isFlag();
                    return Boolean.compare(o1Flag, o2Flag);
                })
                .toList();
    }

    /**
     * 加载波次详情商品数据
     *
     * @param billId
     */
    @Override
    public void loadSortDetail(long billId, boolean state) {
        Params params = new Params();
        params.put("BatchID", billId);
        //1 边检边分-多笼车  2先拣后分-单笼车（东西拣到一起，需要二次分拨） 3单SKU分拣  4按订单分拣
        params.put("SortingType", 1);

        FineExApplication
                .component()
                .http()
                .sortBatchOrderDetail(params)
                .map(new ResponseWrapper<>())
                .flatMap((Function<ArrayList<SortCommodityEntity>, ObservableSource<SortCommodityEntity>>) Observable::fromIterable)
                .filter(carSortDetachEntity -> {
                    if (state) {
                        return carSortDetachEntity.getNeedAmount() <= 0;
                    } else {
                        return carSortDetachEntity.getNeedAmount() > 0;
                    }
                })
                .toList()
                .toObservable()
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<List<SortCommodityEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(List<SortCommodityEntity> info) {
                        if (info == null || info.isEmpty()) {
                            mView.showEmpty();
                        } else {
                            mView.showContent();
                            mView.onSuccess(MessageCreator.createMessage(info, SORT_DETAIL));
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                        mView.showError();
                    }
                });
    }

    /**
     * 确认分拣
     *
     * @param taskEntity
     * @param commodityBean
     */
    @Override
    public void submitSort(TaskEntity taskEntity, SortCommodityEntity commodityBean) {
        ArrayList<Params> list = new ArrayList<>();
        for (int i = 0; i < commodityBean.getOrderBoxBeans().size(); i++) {
            SortCommodityEntity.OrderBoxBean bean = commodityBean.getOrderBoxBeans().get(i);
            Params params = Params.newInstance(Params.Type.MEMBER);
            params.put("sortingType", 1);//1 边检边分-多笼车  2先拣后分-单笼车（东西拣到一起，需要二次分拨） 3单SKU分拣  4按订单分拣
            params.put("batchID", taskEntity.getMainBillID());
            params.put("orderID", bean.getOrderID());
            params.put("posID", commodityBean.getPosID());
            params.put("commodityID", commodityBean.getCommodityId());
            params.put("stockType", commodityBean.getStockType());
            params.put("productBatchID", commodityBean.getProductBatchID());
            params.put("sortAmount", bean.getNeedAmount());
            List<String> containerList = new ArrayList<>();
            containerList.add(bean.getContainerID() + "");
            params.put("containerID", containerList);
            params.put("userID", FineExApplication.component().loginCache().getUserInfo().getUserID());
            list.add(params);
        }

        Params taskParams = new Params();
        taskParams.put("oSDownShelves", list);
        taskParams.put("workID", taskEntity.getWorkID());
        taskParams.put("productCategory", taskEntity.getProductCategory());
        taskParams.put("jobStationID", taskEntity.getJobStationID());
        taskParams.put("appKey", taskEntity.getAppKey());
        taskParams.put("taskWorkID", 0);

        FineExApplication
                .component()
                .http()
                .sortTaskBatchConfirm(taskParams)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<Object>(mView.provideContext()) {
                    @Override
                    public void onSuccess(Object info) {
                        mView.onSuccess(MessageCreator.createMessage(info, SUBMIT_SORT));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }
}
